package com.rongchuan.wt.aspect;

import com.rongchuan.wt.entity.OperationLogRecord;
import com.rongchuan.wt.mapper.OperationLogRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import java.time.LocalDateTime;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Arrays;
import com.rongchuan.wt.annotation.OperationLog;

@Aspect
@Component
public class OperationLogAspect {
    private static final Logger logger = LoggerFactory.getLogger(OperationLogAspect.class);

    @Autowired
    private OperationLogRecordMapper logRecordMapper;

    //切入点
    @Pointcut("@annotation(com.rongchuan.wt.annotation.OperationLog)")
    public void operationLogPointcut() {
    }

    @AfterReturning(pointcut = "operationLogPointcut()")
    public void afterReturning(JoinPoint joinPoint) {
        //1、获取当前被拦截的方法的数据库操作类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        OperationLog operationLog = method.getAnnotation(OperationLog.class);//获取方法上的注解对象
        String description = operationLog.value();//获取描述
        String className = joinPoint.getTarget().getClass().getSimpleName();//获取类名称
        String methodName = method.getName();//获取方法名称
        //2、获取到当前被拦截的方法参数
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0){
            return;
        }
        String params = Arrays.toString(args);
        String operator = "系统用户";//操作人
        LocalDateTime operateTime = LocalDateTime.now();//操作时间
        // 写入数据库
        OperationLogRecord logRecord = OperationLogRecord.builder()
                .className(className) //类名称
                .methodName(methodName) //方法名称
                .description(description) //操作描述
                .params(params) //传递参数
                .operator(operator) //操作人员
                .operateTime(operateTime) //操作时间
                .build();
        logRecordMapper.insert(logRecord);
        logger.info("操作日志: {}.{} - {}，参数: {}", className, methodName, description, params);
    }
} 